/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controlador;

import comu.Configuracio;
import controlador.autogenerats.CampJpaController;
import entity.Camp;
import entity.Producte;
import entity.Productor;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.Query;

/**
 *
 * @author David
 */
public class CampControlador extends CampJpaController{
    
    public CampControlador() {
        super(Persistence.createEntityManagerFactory(Configuracio.PERSISTANCE_UNIT));
    }
    
    public ArrayList<Camp> findCampEntitiesByProducte(Producte producte){
        EntityManager em = getEntityManager();
        try{

        Query q = em.createNativeQuery("SELECT * FROM `camp` WHERE `id` = ANY (Select `camp_id` FROM `produccio` WHERE `productes_id` LIKE "+ producte.getId() +")  order by `nom`", Camp.class);
        Iterator it = q.getResultList().iterator();
        ArrayList<Camp> llista = new ArrayList<Camp>();
        while(it.hasNext()){
            llista.add((Camp) it.next());
        }
        return llista;
        } finally {
            em.close();
        }
    }
    
    public ArrayList<Camp> findCampEntitiesAZ() {
        EntityManager em = getEntityManager();
        try{

        Query q = em.createNativeQuery("SELECT * FROM `camp` order by `nom`", Camp.class);
        Iterator it = q.getResultList().iterator();
        ArrayList<Camp> llista = new ArrayList<Camp>();
        while(it.hasNext()){
            llista.add((Camp) it.next());
        }
        return llista;
        } finally {
            em.close();
        }
    }

    public ArrayList<Camp> findCampEntitiesByProductorIProducte(Productor productor, Producte producte) {
        EntityManager em = getEntityManager();
        try{

        Query q = em.createNativeQuery("SELECT * FROM `camp` WHERE `id` = ANY (Select `camp_id` FROM `produccio` WHERE "
                + "`productes_id` LIKE "+ producte.getId() +" and `productor_id` LIKE "+ productor.getId() + ")  order by `nom`", Camp.class);
        Iterator it = q.getResultList().iterator();
        ArrayList<Camp> llista = new ArrayList<Camp>();
        while(it.hasNext()){
            llista.add((Camp) it.next());
        }
        return llista;
        } finally {
            em.close();
        }
    }
}
